# -*- coding: utf-8 -*-
'''
Created on 2018年6月16日
@author: liaolzl
'''
#1.urlopen函数的第一个参数url
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))

#2.urlopen函数的第二个参数data
#http://httpbin.org/post用来作http测试
#将'word':'hello'字典通过urlopen以parse形式传递过去,返回的数据是json格式
import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding ='utf-8')
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())

#3（1）.urlopen函数的第三个参数timeout
#这次timeout设为1，意为1秒之内该url能够相应就不会报错
import urllib.request
response = urllib.request.urlopen('http://httpbin.org/get',timeout = 1)
print(response.read())
#3（2）.这次将timeout设为0.1
import urllib.request
import socket
import urllib.error
try:
    response = urllib.request.urlopen('http://httpbin.org/get',timeout = 0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason, socket.timeout):
        print('TIME OUT')